<?php
/**
 * Created by PhpStorm.
 * User: kongqi
 * Date: 2019/11/30
 * Time: 22:51
 */

namespace App\Plugin\HostServer\Front;

use App\Plugin\HostServer\Models\PnHostSvCard;
use App\Plugin\HostServer\Models\PnHostSvUser;
use App\TraitClass\CheckFormTrait;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class RechargeController extends BaseController
{
    use CheckFormTrait;
    public function index($type){
        $title='充值';
        $this->setSeo($title,$title,$title);
        if(!in_array($type,['card']))
        {
            return $this->returnError('404','没有这个支付方式',plugin_route('hostserver.user'));
        }
        $this->setModelControllerView($type);
        return $this->display([]);
    }
    /**
     * 充值
     */
    public function recharge($type,Request $request){
        if(!in_array($type,['card']))
        {
            return $this->returnError('404','没有这个支付方式',plugin_route('hostserver.user'));
        }
        return $this->$type($request);

    }
    public function card($request){
        $data = $request->all();
        $check_data = [
            'card_number' => ['required']
        ];

        $error = $this->checkForm($data, $check_data, [], [
            'card_number' => '卡号不存在'
        ]);
        if (count($error) > 0) {
            $errors = $this->checkFormErrorFormat($error);
            return $this->returnErrorApi($errors['msg']);
        }
        //找卡号
        $card=PnHostSvCard::where('status',0)->where('invalid_at','>=',date('Y-m-d H:i:s'))
            ->where('card_number',$data['card_number'])->first();
        if(empty($card))
        {
            return $this->returnErrorApi('卡密失效或不存在');
        }
        DB::beginTransaction();
        //悲观锁住
        $user = PnHostSvUser::lockForUpdate()->find(user('id', 'host_server'));
        $r=PnHostSvUser::recharge($user,$card['money'],$card['id'],'pn_host_server_card','卡密');
        $card->status=1;
        $card->user_id=$user['id'];
        $card->user_name=$user['name'];
        $card->user_at=date('Y-m-d H:i:s');
        $card_r=$card->save();
        if($r && $card_r)
        {

            DB::commit();
            return $this->returnOkApi('充值成功',['url'=>plugin_route('hostserver.user')]);
        }
        DB::rollBack();
        return $this->returnErrorApi('充值失败，请重试');


    }
}